import React, { Component } from 'react';
import './TopProcessBar.less';

export interface topProcessBar {
    props: any,
    state: any,
	bodyDom: any,
	handleScroll: () => void
}

export class topProcessBar extends Component {
	constructor(props) {
		super(props);
		this.state = {
			width: 0,
		};
		this.bodyDom = document.querySelector('body');
	}

	componentDidMount(): void {
		window.addEventListener("scroll", this.handleScroll);
	};

    componentWillUnmount(): void {
        window.removeEventListener('scroll', this.handleScroll)
    }

	handleScroll = () => {
        let { width } = this.state;
        // 兼容手机
		let scrollY = document.documentElement.scrollTop || document.body.scrollTop;
        let newWidth = scrollY / (this.bodyDom.scrollHeight - this.bodyDom.clientHeight) * 100;
        // 防止更新过快
        Math.abs(newWidth - width) > 1 && this.setState({
			width: newWidth
		});
	};

	render() {
		let { width } = this.state;
		return (
			<div className='topProcessBar'>
				<div
                    className='topProcessBar_bar'
                    style={{ width: `${width}%` }}
                />
			</div>
		)
	}
}

export default topProcessBar;